package com.wangmeng.book.server.action;

import com.wangmeng.book.server.Command;
import com.wangmeng.book.server.CommandResult;
import com.wangmeng.book.utils.SpringContextManager;
import com.wangmeng.book.utils.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: 王猛
 * Date: 13-9-24
 * 登陆响应
 */
public class LoginAction implements IBaseAction {

    @Override
    public CommandResult execute(Command cmd) {
        CommandResult cr = new CommandResult();
        cr.setCode(CommandResult.CODE_COMMON_ERROR);
        cr.setMessage("login fail");
        try {
            Map<String, Object> loginData = cmd.getData();
            String dUser = (String) loginData.get("username");
            String pwd = (String) loginData.get("password");
            Long time = (Long) loginData.get("time");
            Long currentTime = new Date().getTime() / 1000;
            if (!StringUtils.isTrimEmpty(dUser) && !StringUtils.isTrimEmpty(pwd) && time != null && Math.abs(currentTime - time) <= 300) {
                JdbcTemplate jt = SpringContextManager.getContext().getBean(JdbcTemplate.class);
                List<Map<String, Object>> list = jt.queryForList("select oid,name,username,pri_level from book_user where username = ? and sha1(concat(password, ? )) = ? ",new Object[]{dUser,time.toString(),pwd});
                if (list.size() > 0) {
                    cr.setCode(CommandResult.CODE_SUCCESS);
                    Map userMap = new HashMap();
                    userMap.putAll(list.get(0));
                    cr.setData(userMap);
                    cr.setMessage(null);
                }
            }
        } catch (Exception ex) {
            cr.setMessage(ex.getMessage());
        }
        return cr;
    }
}
